/************************************************************************
Copyright 2003, 2004, 2005, 2006, 2007, 2008 Grid Technology Research Center,
National Institute of Advanced Industrial Science and Technology.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************/

package jp.aist.gtrc.plus.scheduler.specific.pbs.util;


import java.io.DataInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.log4j.Logger;


public class PBSServerAcceptor implements Runnable {

	private final ServerSocket serverSocket;
	private final PBSScheduleStarter starter;
	private final InetAddress myAddr;

	protected static final Logger logger = Logger.getLogger(PBSServerAcceptor.class);

	public PBSServerAcceptor(PBSServerConfig serverConf, PBSScheduleStarter starter) throws IOException{

		int p = serverConf.getSchedulerPort();
		serverSocket = new ServerSocket(p);
		this.starter = starter;
		myAddr = InetAddress.getLocalHost();

	}

	private PBSSchedulerCommandType getCommand(Socket socket) throws IOException{

		DataInputStream stream = new DataInputStream(socket.getInputStream());
		int value = stream.readInt();
		PBSSchedulerCommandType type = PBSSchedulerCommandType.getType(value);
		logger.info("Command received: " + type.name() + "(" + value + ")");

		return type;

	}

	private boolean isOkToAccept(InetAddress addr) {

		// Only allow scheduling order from my node.
		return addr.equals(myAddr);

	}

	public void run(){

		logger.debug("PBSServerAcceptor Started at " + serverSocket.toString());

		while (true) {
			Socket socket;
			PBSSchedulerCommandType cmd;

			try {
				socket = serverSocket.accept();
				if (isOkToAccept(socket.getInetAddress()) == false) {
					logger.warn("schedule order from unknown host. ignore "
							+ socket.getInetAddress());
					continue;
				}
				cmd = getCommand(socket);
			} catch (IOException e) {
				logger.warn("server socket accept()/read() failed. ignore", e);
				continue;
			}

			if ((cmd != PBSSchedulerCommandType.QUIT)
					&& (cmd.mustRunSchedule() == false)) {
				// ignore ERROR/NULL/CONFIGURE/RULESET orders
				continue;
			}

			starter.runSchedule(new PBSScheduleOrder(cmd, socket));

			if (cmd == PBSSchedulerCommandType.QUIT) {
				try {
					serverSocket.close();
				} catch (IOException e) {
					// ignore
				}
				break;
			}
		}

		logger.debug("PBSServerAcceptor Exited at " + serverSocket.toString());

	}

}
